<!-- 创建换车工单 -->
<template>
  <view class="container">
    <FilterNavbar>
      <template #center>
        <view class="navbar-title"> 创建换车工单 </view>
      </template>
    </FilterNavbar>
    <view class="viewports">
      <ve-form ref="ve_form" :model="form" :rules="rules">
        <ve-card type="none" fold="true">
          <ve-form-item label="订单类型" class="car-origin">
            <ve-radio v-model="form.refType" :list="refTypes" @confirm="refTypeRadioChange" :disabled="form?.type === 'order'" />
          </ve-form-item>
          <ve-form-item label="选择订单号" prop="refId" required>
            <remote-select
              type="all_replace_order_list"
              @change="orderListChange"
              :params="{
                refType: form.refType,
              }"
              v-model="form.refId"
              v-model:label="form.refCode"
              :disabled="form?.type === 'order'"
            />
          </ve-form-item>
          <ve-form-item label="换车人" prop="workOperatorId" required>
            <remote-select
              type="staff_list_changecar"
              @change="operatorListChange"
              :params="{
                siteIdList: [carSiteId],
              }"
              v-model="form.workOperatorId"
              v-model:label="form.realname"
              :disabled="!form.refId ? true : false"
            />
          </ve-form-item>
          <ve-form-item label="换车时间" prop="expectEndTime" :borderBottom="false" required>
            <ve-date-picker v-model="form.expectEndTime" title="时间"></ve-date-picker>
          </ve-form-item>
        </ve-card>
        <ve-card title="订单信息" type="none" :fold="true" v-model:initFold="initExpand">
          <view v-if="orderInfoMsg">
            <!-- <template #forever-show="{ contentIsShow }"> -->
              <ve-cell label="预计租赁周期">{{ orderInfoMsg.startTime }} 至 {{ orderInfoMsg.endTime }}</ve-cell>
              <ve-cell>
                <view class="rent-days">租期：{{ orderInfoMsg.rentDays }}</view>
              </ve-cell>
            <!-- </template> -->
            <ve-cell label="订单来源">{{ orderInfoMsg.orderSourceName }}</ve-cell>
            <ve-cell label="车型">{{ orderInfoMsg.carModelName }}</ve-cell>
            <ve-cell label="交车车型">{{ orderInfoMsg.originalModelName }}</ve-cell>
            <ve-cell label="交车车牌号">{{ orderInfoMsg.carLicenseNo }}</ve-cell>
          </view>
          <view v-else>
            <view class="empty_view">
              <image src="../../../../static/images/empty.png" class="empty_img" />
              <p class="empty_text">暂无订单信息,请先选择订单号</p>
            </view>
          </view>
        </ve-card>
        <ve-card type="none" fold="true">
          <ve-form-item label="车辆来源" class="car-origin">
            <ve-radio v-model="form.carSource" :list="vEnumList" @confirm="radioChange" />
          </ve-form-item>
          <ve-form-item prop="carLicenseNo" v-if="mode == 'default'" label="车牌号">
            <CustomSelectShortOrder
              v-if="form.refType == 1"
              @click="customSelectTap"
              tip="请先选择车辆来源后，再选择车牌号"
              :mode="mode"
              :modelValue="form.carLicenseNo"
            />
            <CustomSelectShortOrder
              v-if="form.refType == 2"
              @click="customSelectTap"
              tip="请先选择车辆来源后，再选择车牌号"
              :mode="mode"
              :modelValue="form.carLicenseNo"
            />
          </ve-form-item>
          <ve-form-item label="排车车型" :borderBottom="false">
            <view>{{ form.carModelName || '-' }}</view>
          </ve-form-item>
        </ve-card>
      </ve-form>
    </view>
    <ve-bottom-box>
      <ve-button type="primary" @click="formSubmit" size="long" :loading="okLoading">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup lang="ts">
  import { onLoad } from '@dcloudio/uni-app'
  import { ref, nextTick, provide } from 'vue'
  import FilterNavbar from '@/components/FilterNavbar'
  import CustomSelectShortOrder from './shortOrder/components/custom-select.vue'
  import CustomSelectLongOrder from './longOrder/components/custom-select.vue'
  import { createReplaceCarWorkAPI } from '@/api/order/workOrder'
  import useFormFold from '@/hooks/useFormFold'
  import dayjs from 'dayjs'
  import { shortorderdetail } from '@/api/dict/detail'
  import { getOrdrDetailsAPI } from '@/api/order/lOrder'

  const initFold1 = ref(true)
  const records = ref(null)
  const isChooseCarId = ref(null)
  const mode = ref('default')
  const initExpand = ref(false)
  const orderInfoMsg = ref(null)
  const noFormSubmit = ref(false)
  const siteIdList = ref(null) //选择换车人的归属门店list
  const carSiteId = ref(null) //选择车辆后的归属门店
  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['refId', 'workOperatorId', 'expectEndTime'],
    },
  ])
  const refTypes = ref([
    { value: 1, label: '短租订单' },
    { value: 2, label: '长租订单' },
  ])
  const vEnumList = ref([
    { value: 1, label: '门店车辆' },
    { value: 3, label: '跨门店调车' },
  ])
  const form = ref({
    refType: 1,
    carSource: 1,
    expectEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  })
  provide('form', form)
  const refTypeRadioChange = (e) => {
    orderInfoMsg.value = undefined

    form.value.refType = e.value
    console.log('form.value.refType', form.value.refType)
    // 清空订单信息
    form.value.refId = undefined
    form.value.refCode = undefined
    form.value.returnCarTime = undefined
    form.value.workOperatorId = undefined
    form.value.realname = undefined
    form.value.expectEndTime = dayjs().format('YYYY-MM-DD HH:mm:ss')

    // 清空车辆信息
    form.value.carId = undefined
    form.value.carLicenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined
  }
  // 选择人
  const operatorListChange = (a, option = {}) => {
    console.log(a)
    console.log(option)
    siteIdList.value = option.siteIdList
    if(form.value.carId){
      const hasValue = siteIdList.value.indexOf(Number(carSiteId.value));
      console.log(hasValue);
      // 如先选择负责人，在选车，然后变更负责人，需判断负责人和车辆的门店是否符合，是则支持创建，否则自动清理车辆，需重新选择
      if(hasValue == -1){
        form.value.carId = undefined
        form.value.carLicenseNo = undefined
        form.value.carModelId = undefined
        form.value.carModelName = undefined
      }
    }
  }
  // 选择订单后
  const orderListChange = (a, option = {}) => {
    orderInfoMsg.value = option
    initExpand.value = true
    console.log(option)

    form.value.workOperatorId = undefined
    form.value.realname = undefined
    form.value.carSource = 1
    form.value.carId = undefined
    form.value.carLicenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined

    isChooseCarId.value = option.carId //换下车（排车图打开时默认选中

    form.value.refId = a
    carSiteId.value = option.siteId
    form.value.siteId = option.siteId
    form.value.returnCarTime = option.endTime
    if (option.orderSource == 2 && !option.carId) {
      toast('您选择的订单匹配的车辆为渠道车辆，请先同平台车辆匹配后再换车')
      noFormSubmit.value = true
    } else {
      noFormSubmit.value = false
    }
  }
  const radioChange = (e) => {
    form.value.carSource = e.value
    console.log(form.value.carSource)
    // 清空车辆信息
    form.value.carId = undefined
    form.value.carLicenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined

  }
  const rules = ref({
    refId: {
      required: true,
      message: '请选择订单号',
    },
    workOperatorId: {
      required: true,
      message: '请选择换车人',
    },
    expectEndTime: {
      required: true,
      message: '请选择换车时间',
    },
  })

  const _param = (obj) => {
    let str = ''
    if (typeof obj == 'object') {
      for (let i in obj) {
        if (obj[i] == undefined) {
          continue
        }
        str += i + '=' + obj[i] + '&'
      }
    }
    return str.replace(/&$/g, '')
  }
  // 点击车牌选择事件
  const customSelectTap = () => {
    if (!form.value.refId || !form.value.workOperatorId || !form.value.expectEndTime) {
      toast('请填写必填项')
      return false
    }
    // 跳转选择车牌号页面
    let startTime = form.value.expectEndTime
    const endTime = form.value.returnCarTime
    if (dayjs(startTime).valueOf() > dayjs(endTime).valueOf()) {
      // 将开始时间设置为实际开始时间
      startTime = orderInfoMsg.value.startTime
    }
    let orderInfo = {
      // 当前选中的车辆 id
      carId: form.value.carId,
      siteId: form.value.carSource == 3 ? undefined : orderInfoMsg.value.siteId,
      siteName: form.value.carSource == 3 ? undefined : orderInfoMsg.value.siteName,
      modelId: form.value.carModelId,
      modelName: form.value.carModelName,
      startTime: startTime, //选订单后 预取
      endTime: endTime, //选订单后的 预还
      carSource: form.value.carSource,
      // 订单来源
      orderSourceName: form.value.orderSourceName, //选订单后
      orderStatus: form.value.orderStatus, //选订单后
    }
    // if (props.mode == 'changeCar') {
    //   // 当前选中的车辆 id
    orderInfo.platoonCarId = isChooseCarId.value
    //   orderInfo.orderStatus = 20
    // }
    var neworderInfo = orderInfo
    neworderInfo.siteId = orderInfoMsg.value.siteId
    neworderInfo.siteName = orderInfoMsg.value.siteName
    let paramStr = _param({
      mode: 'select',
      type: form.value.refType == 1 ? 'short-order' : 'long-order',
      data_json: JSON.stringify({
        ...platoonModelQueryParam.value,
        ...orderInfo,
        carId: form.value.carId,
      }),
      orderInfo_json: JSON.stringify(neworderInfo),
    })
    console.log(orderInfo)
    // return false
    uni.navigateTo({
      url: `/pages/asset/stock/car-stock/selector?${paramStr}`,
    })
  }

  // 选择车牌完成后，函数暴露到上级
  const platoonModelQueryParam = ref({})
  console.log(platoonModelQueryParam.value)

  const toast = (e) => {
    uni.showToast({
      title: e,
      icon: 'none',
    })
  }

  onLoad((options: any) => {
    carSiteId.value = undefined
    console.log('load', options)
    if (options.refType || options.refId || options.refCode || options.carId || options.type) {
      form.value.refType = +options.refType
      form.value.refId = options.refId
      form.value.refCode = options.refCode
      form.value.type = options.type

      isChooseCarId.value = options.carId

      if (options.refType == 1) {
        shortorderdetail({ id: options.refId }).then((res: any) => {
          console.log('shortorderdetail', res)
          const { orderInfo } = res.result
          orderInfoMsg.value = orderInfo
          form.value.siteId = orderInfo.siteId
          form.value.returnCarTime = orderInfo.endTime
          initExpand.value = true
        })
      } else {
        getOrdrDetailsAPI({ id: options.refId }).then((res: any) => {
          console.log('getOrdrDetailsAPI', res)
          const { orderInfo } = res.result
          orderInfoMsg.value = {
            ...orderInfo,
            startTime: orderInfo.expectedUseCarTime,
            endTime: orderInfo.expectedReturnCarTime,
            rentDays: orderInfo.leaseNumberStr,
            carModelName: orderInfo.modelName,
            carLicenseNo: orderInfo.licenseNo,
          }
          form.value.siteId = orderInfo.siteId
          form.value.returnCarTime = orderInfo.endTime
          initExpand.value = true
        })
      }
    }

    // 车型选择完成
    uni.$on('carStock:selectCarOk', (carId, option, queryParam) => {
      console.log(carId)
      console.log(option)
      console.log(queryParam)
      form.value.carId = carId
      form.value.carLicenseNo = option.licenseNo
      form.value.modelId = option.modelId
      form.value.carModelName = option.modelName
      carSiteId.value = queryParam.siteId //车辆归属门店
      // 记录弹窗queryParam
      platoonModelQueryParam.value = { ...queryParam }
      if(form.value.carSource == 3 && form.value.workOperatorId){
        console.log('选择跨门店，有换车人时')
        const hasValue = siteIdList.value.indexOf(Number(queryParam.siteId));
        console.log(hasValue);
        // 如先选择人后选择车辆，同时跨门店调车，之前选择的换车人数据权限不符合车辆的归属门店，则自动清空
        // 需重新选择，此时下拉展示选择车辆归属门店符合数据权限的在职员工
        if(hasValue == -1){
          form.value.workOperatorId = undefined
          form.value.realname = undefined
        }
      }
      if(form.value.carSource == 3){
        carSiteId.value = Number(queryParam.siteId)
      }
    })
  })
  const ve_form = ref(null)
  const okLoading = ref(false)
  const formSubmit = () => {
    if (noFormSubmit.value) {
      toast('您选择的订单匹配的车辆为渠道车辆，请先同平台车辆匹配后再换车')
      return false
    }
    ve_form.value.validate((valid, errors) => {
      console.log(valid)
      if (valid) {
        var res
        var params = {
          ...form.value,
        }
        okLoading.value = true
        createReplaceCarWorkAPI(params)
          .then((res) => {
            if (res.code == 200) {
              toast(res.message)
              uni.$emit('refreshData', 'createChangeCarWorkOrder')
              uni.navigateBack()
            } else {
              toast(res.message)
              return false
            }
          })
          .catch(() => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors)
        console.log('验证失败', errors)
      }
    })
  }
  defineExpose({})
</script>

<style lang="less" scoped>
  .container {
    background: #f7f8fa;
  }

  .viewports {
    display: flex;
    flex-direction: column;
    padding: 24rpx;
  }

  .platoon-model {
    width: 100%;
    background: #f7f8fa;
    padding: 34rpx 24rpx;
    font-size: 30rpx;
    color: #191c27;
  }

  .car-origin {
    /deep/ .ve-form-item__body {
      align-items: center;
    }
  }

  .rent-days {
    color: #3072F6;
    font-size: 30rpx;
    font-weight: 400;
  }

  .empty_view {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 40rpx 0;
  }

  .empty_img {
    width: 64rpx;
    height: 64rpx;
    margin-bottom: 8rpx;
  }

  .empty_text {
    color: #CDCDCD;
    font-size: 24rpx;
  }
</style>
